<template>
  <div class="login-container">
    <div class="login-box">
      <h2>用户管理系统</h2>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <div class="remember-me">
          <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
        </div>
        <el-button
          type="primary"
          :loading="loading"
          class="login-button"
          @click="handleLogin"
        >
          登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { userLogin } from '@/api/user'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    const res = await userLogin({
      username: loginForm.username,
      password: loginForm.password
    })

    // 登录成功处理
    if (res.code === 200) {
      if (loginForm.remember) {
        localStorage.setItem('username', loginForm.username)
        localStorage.setItem('password', loginForm.password)
      } else {
        localStorage.removeItem('username')
        localStorage.removeItem('password')
      }

      // 保存用户信息
      localStorage.setItem('token', res.data.token || 'default-token') // 确保有token值
      localStorage.setItem('userName', res.data.username || 'user') // 设置用户名
      localStorage.setItem('userId', res.data.id?.toString() || '') // 保存用户ID

      ElMessage.success('登录成功')
      // 确保在成功回调中执行路由跳转
      await router.push('/')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 检查是否有保存的登录信息
const checkSavedLogin = () => {
  const savedUsername = localStorage.getItem('username')
  const savedPassword = localStorage.getItem('password')
  if (savedUsername && savedPassword) {
    loginForm.username = savedUsername
    loginForm.password = savedPassword
    loginForm.remember = true
  }
}

checkSavedLogin()
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.login-box {
  width: 350px;
  padding: 35px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  font-size: 22px;
  color: #333;
  font-weight: 500;
}

.login-form {
  margin-top: 20px;
}

.remember-me {
  margin: 15px 0;
}

.login-button {
  width: 100%;
  margin-top: 5px;
  padding: 12px 0;
}

:deep(.el-input__wrapper) {
  padding-left: 0;
}

:deep(.el-input__prefix) {
  margin: 0 8px;
  color: #909399;
}

:deep(.el-checkbox__label) {
  color: #606266;
}
</style> 